package apibasej.log;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

import apibasej.basic.config.ConfigConsumerInterface;
import apibasej.basic.config.ConfigManager;
import apibasej.basic.config.Prop;
/**
 * http://code.google.com/p/apibasej/
 * 
 * @author Julio Azevedo Lessa - apibasej@gmail.com
 * 
 */
public class MySimpleLogFormater extends Formatter implements ConfigConsumerInterface{

	private ConfigManager conf = new ConfigManager();
	@Override
	public <T> T getProp(Prop<T> prop) {
		return conf.getProp(prop);
	}

	private boolean showClassAndMethod = false;
	public boolean isShowClassAndMethod() {
		return showClassAndMethod;
	}
	public void setShowClassAndMethod(boolean showClassAndMethod) {
		this.showClassAndMethod = showClassAndMethod;
	}
	
	@Override
	public String format(LogRecord record) {
		StringWriter line = new StringWriter();
		line.append(new SimpleDateFormat(getProp(PATTERN_DATE_TIME)).format(new Date(record.getMillis())));
		line.append(' ');
		line.append(record.getLoggerName());
		line.append(' ');
		line.append(record.getLevel().getName());
		if(isShowClassAndMethod()){
			line.append(" (");
			line.append(record.getSourceClassName());
			line.append('.');
			line.append(record.getSourceMethodName());
			line.append(')');
		}
		line.append(": ");
		line.append(record.getMessage());
		line.append("\r\n");
		Throwable t = record.getThrown();
		if(t!=null){
			PrintWriter pw = new PrintWriter(line);
			t.printStackTrace(pw);
			pw.close();
		}
		String resp = line.toString();
		try {
			line.close();
		} catch (IOException e) {
			//e.printStackTrace();
		}
		return resp;
	}

}
